
import normalizeWheel from "./vendor/normalizeWheel";
function functionReturnsTrue() {
    return true;
}
function functionReturnsFalse() {
    return false;
}

class WheelHandler {
    private _animationFrameID;
    private _deltaX;
    private _deltaY;
    private _handleScrollX;
    private _stopPropagation;
    private _handleScrollY;
    private _onWheelCallback;

    constructor(onWheel, handleScrollX, handleScrollY, stopPropagation?) {
        this._animationFrameID = null;
        this._deltaX = 0;
        this._deltaY = 0;
        this._didWheel = this._didWheel.bind(this);
        this.onWheel = this.onWheel.bind(this);
        if (typeof handleScrollX !== 'function') {
            handleScrollX = handleScrollX ?
                functionReturnsTrue :
                functionReturnsFalse;
        }

        if (typeof handleScrollY !== 'function') {
            handleScrollY = handleScrollY ?
                functionReturnsTrue :
                functionReturnsFalse;
        }

        if (typeof stopPropagation !== 'function') {
            stopPropagation = stopPropagation ?
                functionReturnsTrue :
                functionReturnsFalse;
        }

        this._handleScrollX = handleScrollX;
        this._handleScrollY = handleScrollY;
        this._stopPropagation = stopPropagation;
        this._onWheelCallback = onWheel;
    }


    onWheel(event, delta) {     
        var normalizedEvent = normalizeWheel(event.originalEvent);
        var deltaX = this._deltaX + normalizedEvent.pixelX;
        var deltaY = this._deltaY + normalizedEvent.pixelY;
        var handleScrollX = this._handleScrollX(deltaX, deltaY);
        var handleScrollY = this._handleScrollY(deltaY, deltaX);
        if (!handleScrollX && !handleScrollY) {
            return;
        }

        this._deltaX += handleScrollX ? normalizedEvent.pixelX : 0;
        this._deltaY += handleScrollY ? normalizedEvent.pixelY : 0;
        event.preventDefault();

        var changed;
        if (this._deltaX !== 0 || this._deltaY !== 0) {
            if (this._stopPropagation()) {
                event.stopPropagation();
            }
            changed = true;
        }

        if (changed === true && this._animationFrameID === null) {
            this._animationFrameID = requestAnimationFrame(this._didWheel);
        }
    }
    _didWheel() {
        this._animationFrameID = null;
        this._onWheelCallback(this._deltaX, this._deltaY);
        this._deltaX = 0;
        this._deltaY = 0;
    }
}

export default WheelHandler;
